package base

import (
	"git.mycaigou.com/gfyx/common/rpc_client"
	"git.mycaigou.com/gfyx/micro-gfyx-api/http_server/controller"
	"git.mycaigou.com/gfyx/micro-gfyx-api/service/base/menu"
	"github.com/gin-gonic/gin"
)

type MenuController struct {
	controller.BaseController
	menuService menu.MenuServiceIface
}

func NewMenuController(menuService menu.MenuServiceIface) *MenuController {
	return &MenuController{
		menuService: menuService,
	}
}

// RegisterRouter
// 注册路由
func (c *MenuController) RegisterRouter(g *gin.RouterGroup) {
	// 获取菜单接口
	g.GET("/menu/list", c.MenuList)
	// 获取当前用户的可见菜单接口
	g.GET("/menu/visible-list", c.MenuVisibleList)
}

func (c *MenuController) MenuList(ctx *gin.Context) {
	list, err := c.menuService.MenuList(ctx, 0)
	if err != nil {
		grpcErr := rpc_client.GetGrpcError(err)
		c.Fail(ctx, grpcErr.GetCode(), grpcErr.GetMessage())
		return
	}

	menuList := make([]map[string]interface{}, 0)
	for _, item := range list {
		menuList = append(menuList, map[string]interface{}{
			"id":              item.Id,
			"parent_id":       item.ParentId,
			"name":            item.Name,
			"icon":            item.Icon,
			"path":            item.Path,
			"sort":            item.Sort,
			"url":             item.Url,
			"url_type":        item.UrlType,
			"is_leaf":         item.IsLeaf,
			"permission_list": item.PermissionList,
			"extend":          item.Extend,
		})
	}

	c.Success(ctx, map[string]interface{}{
		"list": menuList,
	})

}

func (c *MenuController) MenuVisibleList(ctx *gin.Context) {
	list, err := c.menuService.MenuList(ctx, 1)
	if err != nil {
		grpcErr := rpc_client.GetGrpcError(err)
		c.Fail(ctx, grpcErr.GetCode(), grpcErr.GetMessage())
		return
	}
	menuList := make([]map[string]interface{}, 0)
	for _, item := range list {
		menuList = append(menuList, map[string]interface{}{
			"id":              item.Id,
			"parent_id":       item.ParentId,
			"name":            item.Name,
			"icon":            item.Icon,
			"path":            item.Path,
			"sort":            item.Sort,
			"url":             item.Url,
			"url_type":        item.UrlType,
			"is_leaf":         item.IsLeaf,
			"permission_list": item.PermissionList,
			"is_visible":      item.IsSelected,
			"extend":          item.Extend,
		})
	}

	c.Success(ctx, map[string]interface{}{
		"list": menuList,
	})
}
